package exemplo.database;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import exemplo.model.Product;


public class ProductDAO extends DataBaseConnection{

	public ProductDAO() throws SQLException, ClassNotFoundException {
		super();
	}
	
	public boolean add(Product prod) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("INSERT INTO product VALUES (?, ?, ?, ?);");
		ps.setInt(1, prod.getCode());
		ps.setString(2, prod.getName());
		ps.setInt(3, prod.getNumberOfItens());
		ps.setDouble(4, prod.getPrice());
		boolean b = ps.execute();
		ps.close();
		return b;
	}
	
	public boolean set(Product prod) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("UPDATE product SET name = ?, numberOfItens = ?, price = ? WHERE code = ?;");
		ps.setString(1, prod.getName());
		ps.setInt(2, prod.getNumberOfItens());
		ps.setDouble(3, prod.getPrice());
		ps.setInt(4, prod.getCode());
		
		int b = ps.executeUpdate();
		ps.close();
		return b > 0;
	}
	
	public boolean delete(Product prod) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("DELETE FROM product WHERE code = ?;");
		ps.setInt(1, prod.getCode());

		int b = ps.executeUpdate();
		ps.close();
		return b > 0;
	}
	
	public List<Product> getAllProducts() throws SQLException, ClassNotFoundException {
		List<Product> list = new LinkedList<Product>();
		ResultSet rs = getStatement().executeQuery("SELECT * FROM PRODUCT");
		
		while(rs.next()) {
			Product prod = new Product();
			populateProduct(prod, rs);
			list.add(prod);
		}
		rs.close();
		return list;
	}
	
	public Product getByCode(int code) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("SELECT * FROM product WHERE code = ?;");
		ps.setInt(1, code);		
		ResultSet rs = ps.executeQuery();
		if (!rs.next()) return null;
		Product p = new Product();
		populateProduct(p, rs);
		rs.close();
		ps.close();
		return p;
	}
	
	private void populateProduct(Product prod, ResultSet rs) throws SQLException {
		prod.setCode(rs.getInt("code"));
		prod.setName(rs.getString("name"));
		prod.setNumberOfItens(rs.getInt("numberOfItens"));
		prod.setPrice(rs.getDouble("price"));
	}
}
